import Vue from 'vue'
import Router from 'vue-router'
import store from '../store/index'
import routes from './router'
import Cookies from 'js-cookie'
import Home from '../pages/home/Home.vue'
import Login from '../pages/login/Login.vue'
import Register from '../pages/register/Register.vue'
Vue.use(Router)

const router =  new Router({
  routes: [
            {
                path: '/',
                name: 'Home',
                component: Home,
                meta: {
                    requireAuth: true
                }
            }, 
            {
                path: '/login',
                name: 'Login',
                component: Login,
                meta: {
                  requireAuth: true
              }
            },
            {
                path: '/register',
                name: 'Register',
                component: Register
            }
        ]
})

router.beforeEach((to, from, next) => {
  // eslint-disable-next-line no-restricted-syntax
  console.log(to)
  // eslint-disable-next-line no-restricted-syntax
  if (to.matched.some(record  => record.meta.requireAuth)) {
    // eslint-disable-next-line no-restricted-syntax
    const token = Cookies.get('token')
    if (token) {
      if (!store.state.name) {
        const name = localStorage.getItem('name')
        store.dispatch('setInfo',name)
        if (to.path === "/login") {
          next(from)
        } else {
          next()
        }
      } else {
        if (to.path === "/login") {
          next(from)
        } else {
          next()
        }
      }
    } else {
      if (to.path === "/login") {
        next()
      } else {
        next('/login')
      }
    }
  }
  else {
    next()
  }
})

export default router;
// const router = new Router({
//   routes: [{
//     path: '/home/:userId',
//     name: 'Home',
//     components: Home
//   }]
// })

// this.$router.push({name: 'Home',params: {userId: 123}})
